<script setup lang="ts">
import { useColumnsNow } from "./columnsNow";
import { useColumnsHistory } from "./columnsHistory";
import { Plus } from "@element-plus/icons-vue";
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import ProductInfoForm from "./ProductInfoForm.vue";
import { getProductList, getProductDetail } from "@/api/productInfo";
import { getExhibitorId } from "@/utils/getExhibitorId";

defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "productInfo"
});

const searchDataNow = ref(""); // 本届产品搜索
const searchDataHistory = ref(""); // 往届产品搜索
const activeName = ref("first"); // 选项卡

// 产品数据
const currentProductList = ref([]); // 本届产品数据
const previousProductList = ref([]); // 往届产品数据
const loading = ref(false);

// 分页信息
const paginationNow = ref({
  total: 0,
  page: 1,
  limit: 10
});

const paginationHistory = ref({
  total: 0,
  page: 1,
  limit: 10
});

const formMode = ref<"add" | "view" | "edit">("add");
const currentFormData = ref({});

const handleAdd = () => {
  // 处理新增逻辑
  console.log("新增数据");
  formMode.value = "add";
  const exhibitor_id = getExhibitorId();
  currentFormData.value = {
    id: "",
    exhibitor_id: exhibitor_id || 0,
    product_name_cn: "",
    product_name_en: "",
    product_category: "",
    product_intr: "",
    product_img: "",
    status: 3
  };
  isShowEditDialog.value = true;
};

const handleView = async (row: any) => {
  // 处理查看逻辑
  console.log("查看数据", row);
  try {
    const result: any = await getProductDetail(row.id, row.exhibitor_id);
    if (result.code === 1) {
      formMode.value = "view";
      currentFormData.value = result.data;
      isShowEditDialog.value = true;
    } else {
      ElMessage.error(result.msg || "获取产品详情失败");
    }
  } catch (error) {
    console.error("获取产品详情失败:", error);
    ElMessage.error("获取产品详情失败");
  }
};

const handleEdit = async (row: any) => {
  // 处理修改逻辑
  console.log("修改数据", row);
  try {
    const result: any = await getProductDetail(row.id, row.exhibitor_id);
    if (result.code === 1) {
      formMode.value = "edit";
      currentFormData.value = result.data;
      isShowEditDialog.value = true;
    } else {
      ElMessage.error(result.msg || "获取产品详情失败");
    }
  } catch (error) {
    console.error("获取产品详情失败:", error);
    ElMessage.error("获取产品详情失败");
  }
};

// 获取本届产品列表
const getCurrentProductList = async (page = 1, limit = 10) => {
  try {
    loading.value = true;
    const exhibitor_id = getExhibitorId();
    const res: any = await getProductList(
      "current",
      page,
      limit,
      exhibitor_id,
      searchDataNow.value.trim() || undefined
    );
    console.log("本届产品API返回的完整数据:", res);
    console.log("本届产品列表数据:", res.data.list);
    currentProductList.value = res.data.list || [];
    // 更新分页信息
    paginationNow.value = {
      total: res.data.total,
      page: res.data.page,
      limit: res.data.limit
    };
  } catch (error) {
    console.error("获取本届产品列表失败:", error);
    currentProductList.value = [];
  } finally {
    loading.value = false;
  }
};

// 获取往届产品列表
const getPreviousProductList = async (page = 1, limit = 10) => {
  try {
    loading.value = true;
    const exhibitor_id = getExhibitorId();
    const res: any = await getProductList(
      "previous",
      page,
      limit,
      exhibitor_id,
      searchDataHistory.value.trim() || undefined
    );
    console.log("往届产品API返回的完整数据:", res);
    console.log("往届产品列表数据:", res.data.list);
    previousProductList.value = res.data.list || [];
    // 更新分页信息
    paginationHistory.value = {
      total: res.data.total,
      page: res.data.page,
      limit: res.data.limit
    };
  } catch (error) {
    console.error("获取往届产品列表失败:", error);
    previousProductList.value = [];
  } finally {
    loading.value = false;
  }
};

// 本届产品数据
const { tableDataNow, columnsNow } = useColumnsNow(
  currentProductList,
  handleView,
  handleEdit,
  getCurrentProductList
);
// 往届产品数据（传入刷新本届列表的回调）
const { tableDataHistory, columnsHistory } = useColumnsHistory(
  previousProductList,
  () => getCurrentProductList(paginationNow.value.page, 10)
);

// 组件挂载时获取数据
onMounted(() => {
  getCurrentProductList(1, 10);
  getPreviousProductList(1, 10);
});

// 分页改变处理
const handleCurrentChangeNow = (page: number) => {
  paginationNow.value.page = page;
  getCurrentProductList(page, 10);
};

const handleCurrentChangeHistory = (page: number) => {
  paginationHistory.value.page = page;
  getPreviousProductList(page, 10);
};

// 本届产品搜索
const handleSearchNow = () => {
  paginationNow.value.page = 1; // 重置到第一页
  getCurrentProductList(1, 10);
};

// 往届产品搜索
const handleSearchHistory = () => {
  paginationHistory.value.page = 1; // 重置到第一页
  getPreviousProductList(1, 10);
};

// 清空本届产品搜索
const handleClearSearchNow = () => {
  searchDataNow.value = "";
  paginationNow.value.page = 1;
  getCurrentProductList(1, 10);
};

// 清空往届产品搜索
const handleClearSearchHistory = () => {
  searchDataHistory.value = "";
  paginationHistory.value.page = 1;
  getPreviousProductList(1, 10);
};

const handleRefresh = () => {
  // 调用列表查询接口
  console.log("刷新");
  getCurrentProductList(paginationNow.value.page, 10);
  getPreviousProductList(paginationHistory.value.page, 10);
};

const handleCancel = () => {
  isShowEditDialog.value = false;
};

const handleConfirm = (submitData?: any) => {
  // 处理确认逻辑
  console.log("确认提交", submitData);
  isShowEditDialog.value = false;
  // 刷新列表
  handleRefresh();
};

const isShowEditDialog = ref(false);
</script>

<template>
  <div class="tab-container">
    <el-tabs v-model="activeName" type="card" style="background-color: white">
      <el-tab-pane label="本届产品" name="first">
        <!-- 本届产品表格 -->
        <!-- 统一的白色背景容器 -->
        <div class="table-container">
          <!-- 自定义头部 -->
          <div class="custom-header">
            <div class="header-left">
              <div class="search-box">
                <el-input
                  v-model="searchDataNow"
                  style="width: 300px; margin-right: 40px"
                  placeholder="产品名称"
                  clearable
                  @keyup.enter="handleSearchNow"
                  @clear="handleClearSearchNow"
                />
                <el-button type="primary" @click="handleSearchNow"
                  >搜索</el-button
                >
              </div>
            </div>
            <div class="header-right">
              <el-button type="primary" @click="handleAdd">
                <el-icon><Plus /></el-icon>
                提交产品
              </el-button>
            </div>
          </div>

          <!-- 表格 -->
          <pure-table
            :data="tableDataNow"
            :columns="columnsNow"
            :loading="loading"
            stripe
          />

          <!-- 分页组件 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="paginationNow.page"
              :page-size="10"
              :total="paginationNow.total"
              layout="total, prev, pager, next, jumper"
              @current-change="handleCurrentChangeNow"
            />
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="往届产品" name="second">
        <!-- 往届产品表格 -->
        <!-- 统一的白色背景容器 -->
        <div class="table-container">
          <!-- 自定义头部 -->
          <div class="custom-header">
            <div class="header-left">
              <div class="search-box">
                <el-input
                  v-model="searchDataHistory"
                  style="width: 300px; margin-right: 40px"
                  placeholder="产品名称"
                  clearable
                  @keyup.enter="handleSearchHistory"
                  @clear="handleClearSearchHistory"
                />
                <el-button type="primary" @click="handleSearchHistory"
                  >搜索</el-button
                >
              </div>
            </div>
            <div class="header-right">
              <!-- 往届产品不需要新增按钮 -->
            </div>
          </div>

          <!-- 表格 -->
          <pure-table
            :data="tableDataHistory"
            :columns="columnsHistory"
            :loading="loading"
            stripe
          />

          <!-- 分页组件 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="paginationHistory.page"
              :page-size="10"
              :total="paginationHistory.total"
              layout="total, prev, pager, next, jumper"
              @current-change="handleCurrentChangeHistory"
            />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 弹框放在最外层，避免被其他组件影响 -->

    <el-dialog v-model="isShowEditDialog" :top="'25px'">
      <ProductInfoForm
        :mode="formMode"
        :initial-data="currentFormData"
        @cancel="handleCancel"
        @confirm="handleConfirm"
      />
    </el-dialog>
  </div>
</template>

<style scoped>
.tab-container {
  padding: 20px;
  background-color: white;
}

/* 统一的白色背景容器 */
.table-container {
  background-color: #fff;
}

/* 自定义头部样式 */
.custom-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.header-left .header-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 分页容器样式 */
.pagination-container {
  padding: 20px 0;
  text-align: center;
  display: flex;
  justify-content: center;
  width: 100%;
}

/* 修改表头背景色 */
:deep(.el-table__header th) {
  background-color: #f2f2f2 !important;
}

/* 修改斑马纹背景色 */
:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #f2f2f2 !important;
}

/* 选项卡样式（卡片类型） */
:deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
  background-color: #ffffff;
  color: #000000;
  border: 1px solid #e5e5e5;
  border-bottom: none;
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__item.is-active) {
  background-color: #17a1b8;
  color: #ffffff;
  border-color: #17a1b8;
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__nav) {
  border-bottom: 1px solid #e5e5e5;
}
</style>
